package com.social.servlet;

import com.social.dao.UserDAO;
import com.social.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author JiangYunSong
 * @ClassName AddFriend.java
 * @Description TODO
 * @date 2025/6/24 - 16:17
 */

@WebServlet("/addFriend")
public class AddFriend extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        //当前用户的所有好友ID，用逗号分隔的
        String friends = request.getParameter("friends");
        String userId = request.getParameter("userId");
        UserDAO userDAO = new UserDAO();
        List<User> allUsers = userDAO.getAllUsers();
        String[] friendsArray = friends.split(",");
        List<Map<String,Object>> lists=new ArrayList<>();
        //遍历friendsArray，拿每个好友的id去allUsers中查找，看谁还添加了friendId为好友，就把这个人装起来返回给前端
        for (String friendId : friendsArray) {
            for (User user : allUsers) {
                Map<String,Object> map=new HashMap<>();
                //放行当前好友\自己\当前人已是好友
                if (!friendId.equals(user.getId()+"") && !userId.equals(user.getId()+"") && !friends.contains(user.getId()+"")) {
                    if(user.getFriends()!=null&&user.getFriends()!=""&&user.getFriends().contains(friendId)&&(!user.getFriends().contains(userId))){
                        //如果当前用户已经存在于lists里了，就不重复装了
                        boolean exists = false;
                        for (Map<String, Object> map2 : lists) {
                            Object idValue = map2.get("id");
                            if (idValue != null) {
                                if (idValue instanceof Integer && (Integer) idValue == user.getId()) {
                                    exists = true;
                                    break;
                                }
                            }
                        }
                        if(!exists){
                            map.put("nickname",user.getNickname());
                            map.put("id",user.getId());
                            lists.add(map);
                        }
                    }
                }
            }
        }
        session.setAttribute("tjFriend", lists);
        request.getRequestDispatcher("addFriendNew.jsp").forward(request, response);
    }
}
